/************************************************************************************
*                                                                                   *
*   MDX2DAE - MDX to COLLADA converter                                              *
*   Copyright (C) 2010  Gunnar Lilleaasen                                           *
*                                                                                   *
*   This program is free software; you can redistribute it and/or                   *
*   modify it under the terms of the GNU General Public License                     *
*   as published by the Free Software Foundation; either version 2                  *
*   of the License, or (at your option) any later version.                          *
*                                                                                   *
*   This program is distributed in the hope that it will be useful,                 *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of                  *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                   *
*   GNU General Public License for more details.                                    *
*                                                                                   *
*   You should have received a copy of the GNU General Public License               *
*   along with this program; if not, write to the Free Software                     *
*   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. *
*                                                                                   *
************************************************************************************/
#ifndef BUFFER_H_
#define BUFFER_H_

#include <cstdio>
#include <stdexcept>
#include <sstream>
#include <vector>

class Buffer
{
public:
    Buffer(const char* filename) :
      m_buf(NULL), m_size(0)
    {
        FILE* f = NULL;
        int error = fopen_s(&f, filename, "rb");

        if(!error)
        {
            fseek(f, 0, SEEK_END);
            m_size = ftell(f);
            m_buf.resize(m_size);
            fseek(f, 0, SEEK_SET);
            fread(&m_buf[0], sizeof(char), m_size, f);
        
            fclose(f);
        }
        else
        {
            throw std::runtime_error("Failed to open file.");
        }
    }

    ~Buffer()
    {
    }

    template <typename T>
    T* GetPointer(long offset)
    {
        long beg = offset;
        long end = offset + sizeof(T);

        if(end >= m_size || beg < 0 )
        {
            throw std::out_of_range("Out of range.");
        }

        return (T*) (&m_buf[0] + offset);
    }

    long GetSize()
    {
        return m_size;
    }

private:
    std::vector<uint8_t> m_buf;
    long m_size;
};

#endif // BUFFER_H_